package com.ruoyi.zhmk.controller;

import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.zhmk.service.IZhmkPostService;
import com.ruoyi.zhmk.domain.ZhmkDept;
import com.ruoyi.zhmk.domain.ZhmkPost;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.zhmk.domain.ZhmkUser;
import com.ruoyi.zhmk.service.IZhmkUserService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 人员信息Controller
 * 
 * @author sxl
 * @date 2021-06-10
 */
@Controller
@RequestMapping("/zhmk/user")
public class ZhmkUserController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(ZhmkUserController.class);

    private String prefix = "zhmk/user";

    @Autowired
    private IZhmkUserService zhmkUserService;

    @Autowired
    private IZhmkPostService postService;

    @RequiresPermissions("zhmk:user:view")
    @GetMapping()
    public String user()
    {
        return prefix + "/user";
    }

    /**
     * 查询人员信息列表
     */
    @RequiresPermissions("zhmk:user:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ZhmkUser zhmkUser)
    {
        startPage();
        List<ZhmkUser> list = zhmkUserService.selectZhmkUserList(zhmkUser);
        List<ZhmkPost> posts = null;
        String a = "";
        for(ZhmkUser users : list){
            posts = postService.selectPostsByUserId(users.getUserId());
            if(posts.size()>0){
                for (ZhmkPost post : posts)
                {
                    if (post.isFlag())//true
                    {
                        a = a + post.getPostName() + ",";
                    }
                }
                if(a.length()>0){
                    users.setUpdateBy(a.substring(0,a.length()-1));
                }
            }
        }
        return getDataTable(list);
    }

    /**
     * 查询下发人员列表
     */
    @RequiresPermissions("zhmk:user:view")
    @GetMapping("usersend")
    public String sendlist()
    {
        return prefix + "/usersend";
    }

    /**
     * 查询下发人员列表
     */
    @RequiresPermissions("zhmk:user:list")
    @PostMapping("/usersendlist")
    @ResponseBody
    public TableDataInfo usersendlist(ZhmkUser zhmkUser)
    {
        startPage();
        List<ZhmkUser> list = zhmkUserService.selectZhmkUserList(zhmkUser);
        return getDataTable(list);
    }

    /**
     * 导出人员信息列表
     */
    @RequiresPermissions("zhmk:user:export")
    @Log(title = "人员信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ZhmkUser zhmkUser)
    {
        List<ZhmkUser> list = zhmkUserService.selectZhmkUserList(zhmkUser);
        ExcelUtil<ZhmkUser> util = new ExcelUtil<ZhmkUser>(ZhmkUser.class);
        return util.exportExcel(list, "人员信息数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions("zhmk:user:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<ZhmkUser> util = new ExcelUtil<ZhmkUser>(ZhmkUser.class);
        List<ZhmkUser> userList = util.importExcel(file.getInputStream());
        String operName = ShiroUtils.getSysUser().getLoginName(); //查询登录用户名
        String message = zhmkUserService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @RequiresPermissions("zhmk:user:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        ExcelUtil<ZhmkUser> util = new ExcelUtil<ZhmkUser>(ZhmkUser.class);
        return util.importTemplateExcel("人员数据");
    }

    /**
     * 新增人员信息
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        mmap.put("posts", postService.selectPostAll());
        return prefix + "/add";
    }

    /**
     * 新增保存人员信息
     */
    @RequiresPermissions("zhmk:user:add")
    @Log(title = "人员信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated ZhmkUser zhmkUser)
    {
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(zhmkUserService.checkLoginNameUnique(zhmkUser.getUserName())))
        {
            return error("新增用户'" + zhmkUser.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(zhmkUser.getPhonenumber())
                && UserConstants.USER_PHONE_NOT_UNIQUE.equals(zhmkUserService.checkPhoneUnique(zhmkUser)))
        {
            return error("新增用户'" + zhmkUser.getUserName() + "'失败，手机号码已存在");
        }
        zhmkUser.setCreateBy(ShiroUtils.getLoginName()); //登录用户名
        return toAjax(zhmkUserService.insertZhmkUser(zhmkUser));
    }

    /**
     * 修改人员信息
     */
    @GetMapping("/edit/{userId}")
    public String edit(@PathVariable("userId") Long userId, ModelMap mmap)
    {
        mmap.put("posts", postService.selectPostsByUserId(userId)); //查岗位
        mmap.put("zhmkUser", zhmkUserService.selectZhmkUserById(userId));
        return prefix + "/edit";
    }

    /**
     * 添加头像
     */
    @GetMapping("/avatar")
    public String avatar(ModelMap mmap)
    {
       /* SysUser user = ShiroUtils.getSysUser();
        mmap.put("user", zhmkUserService.selectZhmkUserById(user.getUserId()));*/
        return prefix + "/addavatar";
    }

    /**
     * 保存头像
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PostMapping("/addAvatar")
    @ResponseBody
    public AjaxResult addAvatar(@RequestParam("avatarfile") MultipartFile file)
    {
        try
        {
            if (!file.isEmpty())
            {
                FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file);
                return success();
            }
            return error();
        }
        catch (Exception e)
        {
            log.error("添加头像失败！", e);
            return error(e.getMessage());
        }
    }

    /**
     * 编辑头像
     */
    @GetMapping("/avatar/{userId}")
    public String avatar(@PathVariable("userId") Long userId,ModelMap mmap)
    {
        mmap.put("user", zhmkUserService.selectZhmkUserById(userId));
        return prefix + "/avatar";
    }
    /**
     * 保存头像
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PostMapping("/updateAvatar")
    @ResponseBody
    public AjaxResult updateAvatar(@RequestParam("avatarfile") MultipartFile file,@RequestParam("userId") Long id)
    {
       //SysUser currentUser = ShiroUtils.getSysUser();
        ZhmkUser currentUser = zhmkUserService.selectZhmkUserById(id);
        try
        {
            if (!file.isEmpty())
            {
                String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file);
                currentUser.setAvatar(avatar);
                if (zhmkUserService.updateUserInfo(currentUser) > 0)
                {
                    //ShiroUtils.setZhmkUser(zhmkUserService.selectZhmkUserById(currentUser.getUserId()));
                    return success();
                }
            }
            return error();
        }
        catch (Exception e)
        {
            log.error("修改头像失败！", e);
            return error(e.getMessage());
        }
    }

    /**
     * 修改保存人员信息
     */
    @RequiresPermissions("zhmk:user:edit")
    @Log(title = "人员信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ZhmkUser zhmkUser)
    {
        //userService.checkUserAllowed(zhmkUser);
        if (StringUtils.isNotEmpty(zhmkUser.getPhonenumber())
                && UserConstants.USER_PHONE_NOT_UNIQUE.equals(zhmkUserService.checkPhoneUnique(zhmkUser)))
        {
            return error("修改用户'" + zhmkUser.getUserName() + "'失败，手机号码已存在");
        }
        zhmkUser.setUpdateBy(ShiroUtils.getLoginName());
        return toAjax(zhmkUserService.updateZhmkUser(zhmkUser));
    }

    /**
     * 删除人员信息
     */
    @RequiresPermissions("zhmk:user:remove")
    @Log(title = "人员信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(zhmkUserService.deleteZhmkUserByIds(ids));
    }

    /**
     * 校验用户名
     */
    @PostMapping("/checkLoginNameUnique")
    @ResponseBody
    public String checkLoginNameUnique(ZhmkUser user)
    {
        return zhmkUserService.checkLoginNameUnique(user.getUserName());
    }

    /**
     * 校验手机号码
     */
    @PostMapping("/checkPhoneUnique")
    @ResponseBody
    public String checkPhoneUnique(ZhmkUser user)
    {
        return zhmkUserService.checkPhoneUnique(user);
    }

    /**
     * 人员状态修改
     */
    @Log(title = "人员管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("zhmk:user:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(ZhmkUser user)
    {
        //userService.checkUserAllowed(user);
        return toAjax(zhmkUserService.changeStatus(user));
    }

    /**
     * 用户职务显示(未完成)
     */
    @PostMapping( "/searchPostsByUserId")
    @ResponseBody
    public AjaxResult searchPostsByUserId( ZhmkUser user) {
        List<ZhmkPost> list = postService.selectPostsByUserId(user.getUserId());
        String a  =  "";
        for (ZhmkPost post : list)
        {
                if (post.isFlag())//true
                {
                    a = a + post.getPostName();
                }
        }
        return AjaxResult.success(a);
    }

   /* public List<Ztree> treeDataExcludeChild(@PathVariable(value = "excludeId", required = false) Long excludeId)
    {
        ZhmkDept dept = new ZhmkDept();
        dept.setDeptId(excludeId);
        List<Ztree> ztrees = zhmkDeptService.selectDeptTreeExcludeChild(dept);
        return ztrees;
    }*/
}
